﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Collections.Specialized;

namespace BillingSystem
{
    public static class iNet
    {
        static string lastException = "";
        /// <summary>
        /// Последнее пойманое исключение.
        /// </summary>
        public static string LastException { get { return iNet.lastException; } }

        static bool wasException;
        /// <summary>
        /// Было ли исключение во время последнего вызова?
        /// </summary>
        public static bool WasException { get { return iNet.wasException; } }

        public static Stream GetFile(string url)
        {
            try
            {
                WebRequest r = WebRequest.Create(url);
                r.Credentials = CredentialCache.DefaultCredentials;
                ((HttpWebRequest)r).UserAgent = ".NET Framework Example Client";
                WebResponse re = r.GetResponse();
                //MessageBox.Show(((HttpWebResponse)re).StatusDescription);
                Stream data = re.GetResponseStream();
                //re.Close();
                wasException = false;
                return data;
            }
            catch (WebException e)
            {
                lastException = url + "\r\n\r\n" + e.Message;
                wasException = true;
                return null;
            }
        }

        public static bool SaveToFile(string url, string path)
        {
            Stream str = GetFile(url);
            Bitmap bmp;
            try
            {
                bmp = new Bitmap(str);
            }
            catch (Exception e)
            {
                lastException = e.Message;
                wasException = true;
                return false;
            }
            bmp.Save(path);
            return true;
        }

        public static Bitmap GetImg(string url)
        {
            try
            {
                Stream data = GetFile(url);
                if (wasException) return null;
                Bitmap bmp = new Bitmap(data);
                data.Close();
                wasException = false;
                return bmp;
            }
            catch (WebException e)
            {
                lastException = url + "\r\n\r\n" + e.Message;
                wasException = true;
                return null;
            }
        }
    }
}
